#include "DynamicArray.h"

struct DynamciArray
{
    ElementType *array; // 数组指针
    int capacity;       // 数组容量
    int size;           // 元素个数
};

DArray *InitDArray()
{
    DArray *a = (DArray *)malloc(sizeof(DArray));
    if (a == NULL)
    {
        printf("InitDArray malloc error!\n");
        exit(-1); // 退出程序
    }
    a->size = 0;
    a->capacity = 10;
    a->array = (ElementType *)malloc(sizeof(ElementType) * (a->capacity));
    if (a == NULL)
    {
        printf("InitDArray array malloc error!\n");
        exit(-1);
    }
    return a;
}


void InsertDArray(DArray *a, ElementType element)//扩容capacity，申请空间
{
    if (a->size == a->capacity)
    {
        a->capacity *= 2;
        a->array = (ElementType *)realloc(a->array, a->capacity * sizeof(ElementType));
        if (a->array == NULL)
        {
            printf("InitDArray realloc error!\n");
            exit(-1);
        }
    }
    a->array[a->size++] = element;
}

void PrintDArray(DArray *a, void (*print)(ElementType))
{
    printf("capacity:%d   size:%d\n", a->capacity, a->size);
    for (int i = 0; i < a->size; i++)
    {
        print(a->array[i]);
    }
    printf("\n");
}

ElementType FindByElement(DArray *a, ElementType value, bool (*compare)(ElementType, ElementType))
{
    for (int i = 0; i < a->size; i++)
    {
        if (compare(a->array[i], value))
            return a->array[i];
    }
    return NULL;
}

// void RemoveDArray(DArray *a, ElementType value, bool (*compare)(ElementType, ElementType))
// {
//     int i=0;
//     for ( i = 0; i < a->size; i++)
//     {
//         if (compare(a->array[i], value))
//             break;
//     }
//     for (int j = i; j < a->size; j++)
//     {
//         a->array[j] = a->array[j + 1];
//         a->size--;
//     }
// }

ElementType RemoveByIndex(DArray *a, int index)
{
    ElementType result = a->array[index];
    for(int i=index;i<a->size-1;i++)
        a->array[i]=a->array[i+1];
    a->size--;
    return result;
}

ElementType RemoveDArray(DArray *a, ElementType value, bool (*compare)(ElementType, ElementType))
{
    for (int i = 0; i < a->size; i++)
    {
        if (compare(a->array[i],value))
            return RemoveByIndex(a,i);
    }
    return NULL;
}

void ClearDArray(DArray *a, void (*clear)(ElementType))
{
    if (a != NULL)
    {
        for (int i = 0; i < a->size; i++)
        {
            clear(a->array[i]);
        }
        free(a->array);
        free(a);
    }
}




